import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import Header from './Header';
import './Settings.css';

const Settings = () => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  
  // Check for mock authentication
  const isAuthenticated = !!localStorage.getItem('mockAuthToken');
  
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/auth');
    }
  }, [isAuthenticated, navigate]);
  
  // Get user data from localStorage
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('account');
  const [settings, setSettings] = useState({
    account: {
      email: '',
      phone: '',
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    },
    privacy: {
      profileVisibility: 'public',
      photoVisibility: 'friends',
      allowSearch: true,
      showEmail: false
    },
    notifications: {
      emailNotifications: true,
      pushNotifications: false,
      photoComments: true,
      albumShares: true,
      newFollowers: true
    }
  });
  
  useEffect(() => {
    // Simulate loading user data and settings
    const timer = setTimeout(() => {
      const userData = JSON.parse(localStorage.getItem('mockUser') || '{}');
      setUser(userData);
      
      // Set initial settings values
      setSettings(prev => ({
        ...prev,
        account: {
          ...prev.account,
          email: userData.email || '',
          phone: userData.phone || ''
        }
      }));
      
      setIsLoading(false);
    }, 800);
    
    return () => clearTimeout(timer);
  }, []);
  
  const handleAccountChange = (e) => {
    const { name, value } = e.target;
    setSettings(prev => ({
      ...prev,
      account: {
        ...prev.account,
        [name]: value
      }
    }));
  };
  
  const handlePrivacyChange = (e) => {
    const { name, value, type, checked } = e.target;
    setSettings(prev => ({
      ...prev,
      privacy: {
        ...prev.privacy,
        [name]: type === 'checkbox' ? checked : value
      }
    }));
  };
  
  const handleNotificationChange = (e) => {
    const { name, checked } = e.target;
    setSettings(prev => ({
      ...prev,
      notifications: {
        ...prev.notifications,
        [name]: checked
      }
    }));
  };
  
  const handleSaveAccount = (e) => {
    e.preventDefault();
    // In a real app, this would call an API to update the user account
    console.log('Saving account settings:', settings.account);
    
    // Update user data in localStorage
    const updatedUser = {
      ...user,
      email: settings.account.email,
      phone: settings.account.phone
    };
    localStorage.setItem('mockUser', JSON.stringify(updatedUser));
    setUser(updatedUser);
    
    // Clear password fields
    setSettings(prev => ({
      ...prev,
      account: {
        ...prev.account,
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }));
    
    alert(t('settings.accountSaved'));
  };
  
  const handleSavePrivacy = () => {
    // In a real app, this would call an API to update privacy settings
    console.log('Saving privacy settings:', settings.privacy);
    alert(t('settings.privacySaved'));
  };
  
  const handleSaveNotifications = () => {
    // In a real app, this would call an API to update notification settings
    console.log('Saving notification settings:', settings.notifications);
    alert(t('settings.notificationsSaved'));
  };
  
  const handleLanguageChange = (lang) => {
    i18n.changeLanguage(lang);
  };
  
  if (isLoading) {
    return (
      <div className="settings-container">
        <div className="settings-loading">
          <div className="spinner"></div>
          <p>{t('settings.loading')}</p>
        </div>
      </div>
    );
  }
  
  return (
    <div className="settings-container">
      <Header />
      <div className="settings-content">
        <div className="settings-header">
          <h1>{t('settings.title')}</h1>
          <p>{t('settings.subtitle')}</p>
        </div>
        
        <div className="settings-layout">
          <div className="settings-tabs">
            <button 
              className={`tab-btn ${activeTab === 'account' ? 'active' : ''}`}
              onClick={() => setActiveTab('account')}
            >
              {t('settings.accountTab')}
            </button>
            <button 
              className={`tab-btn ${activeTab === 'privacy' ? 'active' : ''}`}
              onClick={() => setActiveTab('privacy')}
            >
              {t('settings.privacyTab')}
            </button>
            <button 
              className={`tab-btn ${activeTab === 'notifications' ? 'active' : ''}`}
              onClick={() => setActiveTab('notifications')}
            >
              {t('settings.notificationsTab')}
            </button>
            <button 
              className={`tab-btn ${activeTab === 'language' ? 'active' : ''}`}
              onClick={() => setActiveTab('language')}
            >
              {t('settings.languageTab')}
            </button>
          </div>
          
          <div className="settings-panel">
            {activeTab === 'account' && (
              <div className="account-settings">
                <h2>{t('settings.accountTitle')}</h2>
                <form onSubmit={handleSaveAccount}>
                  <div className="form-group">
                    <label htmlFor="email">{t('settings.email')}</label>
                    <input
                      type="email"
                      id="email"
                      name="email"
                      value={settings.account.email}
                      onChange={handleAccountChange}
                      required
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="phone">{t('settings.phone')}</label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      value={settings.account.phone}
                      onChange={handleAccountChange}
                    />
                  </div>
                  
                  <div className="form-divider">
                    <h3>{t('settings.changePassword')}</h3>
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="currentPassword">{t('settings.currentPassword')}</label>
                    <input
                      type="password"
                      id="currentPassword"
                      name="currentPassword"
                      value={settings.account.currentPassword}
                      onChange={handleAccountChange}
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="newPassword">{t('settings.newPassword')}</label>
                    <input
                      type="password"
                      id="newPassword"
                      name="newPassword"
                      value={settings.account.newPassword}
                      onChange={handleAccountChange}
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="confirmPassword">{t('settings.confirmPassword')}</label>
                    <input
                      type="password"
                      id="confirmPassword"
                      name="confirmPassword"
                      value={settings.account.confirmPassword}
                      onChange={handleAccountChange}
                    />
                  </div>
                  
                  <button type="submit" className="save-btn">
                    {t('settings.saveAccount')}
                  </button>
                </form>
              </div>
            )}
            
            {activeTab === 'privacy' && (
              <div className="privacy-settings">
                <h2>{t('settings.privacyTitle')}</h2>
                
                <div className="setting-group">
                  <h3>{t('settings.profileVisibility')}</h3>
                  <div className="radio-group">
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="profileVisibility"
                        value="public"
                        checked={settings.privacy.profileVisibility === 'public'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.public')}</span>
                    </label>
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="profileVisibility"
                        value="friends"
                        checked={settings.privacy.profileVisibility === 'friends'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.friends')}</span>
                    </label>
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="profileVisibility"
                        value="private"
                        checked={settings.privacy.profileVisibility === 'private'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.private')}</span>
                    </label>
                  </div>
                </div>
                
                <div className="setting-group">
                  <h3>{t('settings.photoVisibility')}</h3>
                  <div className="radio-group">
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="photoVisibility"
                        value="public"
                        checked={settings.privacy.photoVisibility === 'public'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.public')}</span>
                    </label>
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="photoVisibility"
                        value="friends"
                        checked={settings.privacy.photoVisibility === 'friends'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.friends')}</span>
                    </label>
                    <label className="radio-option">
                      <input
                        type="radio"
                        name="photoVisibility"
                        value="private"
                        checked={settings.privacy.photoVisibility === 'private'}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.private')}</span>
                    </label>
                  </div>
                </div>
                
                <div className="setting-group">
                  <h3>{t('settings.otherSettings')}</h3>
                  <div className="checkbox-group">
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="allowSearch"
                        checked={settings.privacy.allowSearch}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.allowSearch')}</span>
                    </label>
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="showEmail"
                        checked={settings.privacy.showEmail}
                        onChange={handlePrivacyChange}
                      />
                      <span>{t('settings.showEmail')}</span>
                    </label>
                  </div>
                </div>
                
                <button className="save-btn" onClick={handleSavePrivacy}>
                  {t('settings.savePrivacy')}
                </button>
              </div>
            )}
            
            {activeTab === 'notifications' && (
              <div className="notification-settings">
                <h2>{t('settings.notificationsTitle')}</h2>
                
                <div className="setting-group">
                  <h3>{t('settings.notificationMethods')}</h3>
                  <div className="checkbox-group">
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="emailNotifications"
                        checked={settings.notifications.emailNotifications}
                        onChange={handleNotificationChange}
                      />
                      <span>{t('settings.emailNotifications')}</span>
                    </label>
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="pushNotifications"
                        checked={settings.notifications.pushNotifications}
                        onChange={handleNotificationChange}
                      />
                      <span>{t('settings.pushNotifications')}</span>
                    </label>
                  </div>
                </div>
                
                <div className="setting-group">
                  <h3>{t('settings.notificationTypes')}</h3>
                  <div className="checkbox-group">
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="photoComments"
                        checked={settings.notifications.photoComments}
                        onChange={handleNotificationChange}
                      />
                      <span>{t('settings.photoComments')}</span>
                    </label>
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="albumShares"
                        checked={settings.notifications.albumShares}
                        onChange={handleNotificationChange}
                      />
                      <span>{t('settings.albumShares')}</span>
                    </label>
                    <label className="checkbox-option">
                      <input
                        type="checkbox"
                        name="newFollowers"
                        checked={settings.notifications.newFollowers}
                        onChange={handleNotificationChange}
                      />
                      <span>{t('settings.newFollowers')}</span>
                    </label>
                  </div>
                </div>
                
                <button className="save-btn" onClick={handleSaveNotifications}>
                  {t('settings.saveNotifications')}
                </button>
              </div>
            )}
            
            {activeTab === 'language' && (
              <div className="language-settings">
                <h2>{t('settings.languageTitle')}</h2>
                
                <div className="setting-group">
                  <h3>{t('settings.selectLanguage')}</h3>
                  <div className="language-options">
                    <button 
                      className={`language-option ${i18n.language === 'en' ? 'active' : ''}`}
                      onClick={() => handleLanguageChange('en')}
                    >
                      <span className="flag">🇺🇸</span>
                      <span>English</span>
                    </button>
                    <button 
                      className={`language-option ${i18n.language === 'zh' ? 'active' : ''}`}
                      onClick={() => handleLanguageChange('zh')}
                    >
                      <span className="flag">🇨🇳</span>
                      <span>中文</span>
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Settings;